<?php
$host = $_SERVER['HTTP_HOST'];
if ($_SERVER['SERVER_NAME'] == 'localhost'){$uri="/kalender";}else{$uri="";}
		
if (!is_object($bd)){	
	//me conecto a la base de datos
	require("../globals/Db.class.php");
	require("../globals/Conf.class.php");
	$bd=Db::getInstance();	
}
	
function is_valid_email($email){
  $result = 'TRUE';
  if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email)) {
    $result = 'FALSE';
  }
  return $result;
}

//funcion que asigna una nueva password
function get_rand_pass($length){
	$codelenght = $length;
	$newcode_length = 0;
	while($newcode_length < $codelenght) {
	$part = rand(1,3);
	if($part==1){$a=48;$b=57;}  // Numbers
	if($part==2){$a=65;$b=90;}  // UpperCase
	if($part==3){$a=97;$b=122;} // LowerCase
	$code_part=chr(rand($a,$b));
	$newcode_length = $newcode_length + 1;
	$newcode = $newcode.$code_part;
	}	
	return $newcode;
}


//recupero los campos que escribi� el usuario.
$email = $bd->san($_POST["email"]);

if ($email!='' && is_valid_email($email)=='TRUE' ){	
	$query = "select id, usuario, email from usuarios where UPPER(email) = '".strtoupper($email)."' and bloqueado = 0";
	$result = $bd->eje($query);
	$cant = $bd->numRows($result);
	if ($cant > 0 && $cant == 1){
		$row = $bd->fila($result);
		$password = get_rand_pass(10);
		$query = "update usuarios set password = '".substr(sha1($password), 0, 20)."' where UPPER(email) = '".strtoupper($email)."';";
		$bd->eje($query);

		
		$subject = "Kalender - Reset Password";
		$message = "<br/><br/>".
					"Password: $password<br/><br/>".
					"<br/>Kalender ".date("Y");
		$from = "info@kalender.com";
		$headers = "From: \"Kalender\" <".$from.">\r\n"; 
		$headers .= "MIME-Version: 1.0\r\n";
		$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
		mail($email,$subject,$message,$headers);	
		echo "<script language=Javascript> location.href='http://$host$uri/reset_password.php?ok=1'; </script>";	
	}else{
		echo "<script language=Javascript> location.href='http://$host$uri/reset_password.php?error=1'; </script>";
	}
	
}else{
	//faltan datos
	echo "<script language=Javascript> location.href='http://$host$uri/reset_password.php?error=1'; </script>";
}
?>